package features.advance.jdk.dynamicproxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author LIN
 * @date 2021-04-26
 */
public class CGlibProxy implements MethodInterceptor {

    public Object createProxy(Object target){
        // cglib的增强器
        Enhancer enhancer = new Enhancer();
        // 设置被代理类
        enhancer.setSuperclass(target.getClass());
        // 设置代理类
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGlib前置增强");
        Object obj = methodProxy.invokeSuper(o, objects);
        System.out.println("CGlib后置增强");
        return obj;
    }
}
